﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kooboo.Commerce.AddIn;

using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Promotions.Cashback
{
    [Export(typeof(IPromotion))]
    public class Promotion : IPromotion
    {
        #region IPromotion Members

        public string Name
        {
            get { return "Cashback"; }
        }

        public string HeadLine
        {
            get {
                return "Cashback";
            }
        }

        public IPromotionViews Views
        {
            get {
                return new PromotionViews();
            }
        }

        public void RemoveSettings(IPromotionRule rule, Kooboo.Connect.User user)
        {
            Services.Current.Remove(rule);
        }

        public bool Execute(IPromotionRule rule, Connect.User user, PromotionContext context)
        {
            var settings = Services.Current.Find(rule);
            if (settings != null)
            {
                var total = context.Total;

                if (settings.FromTotal.HasValue && settings.ToTotal.HasValue)
                {
                    if (total > settings.FromTotal.Value && total < settings.ToTotal.Value)
                    {
                        context.Discount += settings.ReturnAmount;
                        context.Total -= settings.ReturnAmount;
                        return true;
                    }
                }
                else if (settings.FromTotal.HasValue)
                {
                    if (total > settings.FromTotal)
                    {
                        context.Discount += settings.ReturnAmount;
                        context.Total -= settings.ReturnAmount;
                        return true;
                    }
                }
                else if (settings.ToTotal.HasValue)
                {
                    if (total < settings.ToTotal.Value)
                    {
                        context.Discount += settings.ReturnAmount;
                        context.Total -= settings.ReturnAmount;
                        return true;
                    }
                }

            }

            return false;
        }

        #endregion
    }
}